package indi.lqzhi.tcpserver.handler;


import indi.lqzhi.tcpserver.message.BusMessage;
import indi.lqzhi.tcpserver.manager.BusManager;
import indi.lqzhi.tcpserver.pipeline.BusPipeline;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * @Author: LQZhi
 * @ClassName: BusChannelHandler
 * @Date: 2021-09-26 16-58
 * @Description: 总线处理器，多例，接收服务器的数据，存储在总线中，总线通过线程进行分发给其它客户端
 * @Version: V1.0
 */
@Slf4j
@ChannelHandler.Sharable
public class BusChannelHandler extends ChannelInboundHandlerAdapter{


    /**
     * 总线管理者
     */
    private final Optional<BusManager> manager;

    /**
     * 总线通道
     */
    private final Optional<BusPipeline> pipeline;

    /**
     * 构造器
     * @param manager 总线管理者
     * @param pipeline 总线通道
     */
    public BusChannelHandler(BusManager manager, BusPipeline pipeline) {
        this.manager = Optional.ofNullable(manager);
        this.pipeline = Optional.ofNullable(pipeline);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Channel channel = ctx.channel();
        manager.ifPresent(v -> v.register(channel.id().asLongText(), channel));
        log.debug("注册客户端：{}",channel.id().asLongText());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Channel channel = ctx.channel();
        manager.ifPresent(v -> v.unregister(channel.id().asLongText(), channel));
        log.debug("移除客户端：{}",channel.id().asLongText());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf)msg;
        byte[] bytes=new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        pipeline.ifPresent(v -> v.sendReadMessage(BusMessage.of(null, bytes)));//发送读取到的数据
        log.debug("接收到了：{}",new String(bytes,StandardCharsets.US_ASCII));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        //异常事件
        log.error("发送了异常：",cause);
    }

}
